package cn.com.websocket.handle;

import cn.com.websocket.po.Message;

import javax.websocket.Session;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class SocketHandle {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    public static AtomicInteger onlineNum = new AtomicInteger();
    // 存用户的离线消息（key:用户id，离线消息条数）____ 每一个key对应双方离线记录(getOfflineMsgKey(formUser,toUser))
    public static Map<String,List<Message>> offlineMessage = new ConcurrentHashMap<>();
    // 历史消息(双方聊天记录)  ____  每一个key对应双方记录(getHistorySourceWithTargetKey(source,target))
    public static Map<String, List<Message>> historyMessage = new ConcurrentHashMap<>();
    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    public static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();


    /**
     * <p>获取当前用户(toUser)的离线消息Key(仅用在记录未读消息数据集)</p>
     * @param formUser 源
     * @param toUser   目标
     * */
    public static String getOfflineMsgKey(String formUser,String toUser){
        return String.format("offline_%s:%s",toUser,formUser);
    }



    /**
     * <p>获取双方历史记录key</p>
     * @param source (form)
     * @param target (to)
     * @return
     * */
    public static String getHistorySourceWithTargetKey(String source,String target){
        return String.format("source:%s_target:%s",source,target);
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }
    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
    public static AtomicInteger getOnlineNumber() {
        return onlineNum;
    }
    public static ConcurrentHashMap<String, Session> getSessionPools() {
        return sessionPools;
    }

}
